package com.wu.cloud.userservice.service.impl;

import com.wu.cloud.userservice.configuration.MyUserDetails;
import com.wu.cloud.userservice.service.UserAccountService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author xwu36
 */
@Service
@Slf4j
public class MyUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    @Qualifier("userAccountServiceImpl")
    UserAccountService userAccountService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        List<Map<String, Object>> users = userAccountService.findUserByUserName(s);
        if (users.size() == 0) {
            log.error(s + "用户不存在");
            throw new UsernameNotFoundException("用户不存在");
        }
        Map<String, Object> user = users.get(0);
        MyUserDetails myUserDetails = new MyUserDetails();
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_" + user.get("role").toString()));
        myUserDetails.setUsername(user.get("userId").toString());
        myUserDetails.setPassword(user.get("userKey").toString());
        myUserDetails.setEnable(Integer.parseInt(user.get("userState").toString()) == 0);
        myUserDetails.setRoleList(authorities);
        return myUserDetails;
    }
}
